package com.csu.mypetstore.api.controller.front;


import com.csu.mypetstore.api.common.CommonResponse;
import com.csu.mypetstore.api.common.ResponseCode;
import com.csu.mypetstore.api.entity.Account;
import com.csu.mypetstore.api.entity.SignOn;
import com.csu.mypetstore.api.service.AccountService;
import com.csu.mypetstore.api.util.CreateImageCode;
import com.csu.mypetstore.api.util.KaptchaUtils;
import com.csu.mypetstore.api.vo.AccountVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zhenzi.sms.ZhenziSmsClient;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/account/")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Resource
    private DefaultKaptcha kaptchaProducer;


    private String apiUrl = "https://sms_developer.zhenzikj.com";//这个不用改//短信平台相关参数
    private String appId = "111129";   //榛子云系统上获取
    private String appSecret = "e5dbb017-4d89-41c1-bbde-6dbc1d4690c9\n";

    @RequestMapping("/sendSms")
    @ResponseBody
    public String sendSms(String memPhone,  HttpSession httpSession, Model model) {
        try {
            JSONObject json = null;

            String code = String.valueOf(new Random().nextInt(999999));       //随机生成验证码
            System.out.println(memPhone);
            ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);//将验证码通过榛子云接口发送至手机

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("number", memPhone);     //前台输入的手机号
            params.put("templateId", 8529);  //这个模板id对应的是榛子云个人中心的模板id
            String[] templateParams = new String[2];
            templateParams[0] = code;
            templateParams[1] = "5分钟";
            params.put("templateParams", templateParams);
            String result = client.send(params);
            System.out.println(result);

            json = JSONObject.parseObject(result);
            if (json.getIntValue("code") != 0) {//发送短信失败
                model.addAttribute("message2", "Error");
                model.addAttribute("code1", json);
            }
            else {//将验证码存到session中,同时存入创建时间
                model.addAttribute("message2", "Success");
            }
            json = new JSONObject();
            json.put("memPhone", memPhone);
            json.put("code", code);
            json.put("createTime", System.currentTimeMillis());
            httpSession.setAttribute("code", json);
            System.out.println(code);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("message2", "Error");
        }
        return null;
    }

    @GetMapping("/ImageCode")
    @ResponseBody
    public Map<String, String> ImageCode(HttpServletRequest request) throws IOException {
        Map<String, String> result = new HashMap<>();
        CreateImageCode createImageCode = new CreateImageCode();
        // 获取验证码
        String securityCode = createImageCode.getCode();
        // 验证码存入session
        String key = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        request.getServletContext().setAttribute(key, securityCode);
        // 生成图片
        BufferedImage image = createImageCode.getBuffImg();
        //进行base64编码
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", bos);
        String string = Base64Utils.encodeToString(bos.toByteArray());
        result.put("key", key);
        result.put("image", string);
        return result;
    }

    public static final String LOGIN_VALIDATE_CODE = "login_validate_code";
    @GetMapping("/loginValidateCode")
    public void loginValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        KaptchaUtils.validateCode(request,response,kaptchaProducer,LOGIN_VALIDATE_CODE);
    }

    //登录
    @PostMapping("login")
    @ResponseBody
    public CommonResponse<AccountVO> login(@RequestParam String username,
                                           @RequestParam String password,
                                           HttpSession session,
                                           HttpServletRequest request) {


            System.out.println(username+password);
            CommonResponse<AccountVO> response = accountService.getAccount(username, password);
            if (response.isSuccess()) {
                session.setAttribute("login_account", response.getData());
            }
            System.out.println(response.isSuccess());
            System.out.println(response.getData());
            return response;
    }


    //获取登录用户信息
    @PostMapping("get_login_account_info")
    @ResponseBody
    public CommonResponse<AccountVO> getLoginAccountInfo(HttpSession session) {
        AccountVO loginAccount = (AccountVO) session.getAttribute("login_account");

        if (loginAccount != null) {
            CommonResponse<AccountVO> response=accountService.getAccount(loginAccount.getUsername());
            session.setAttribute("login_account", response.getData());
            loginAccount = (AccountVO) session.getAttribute("login_account");
            return CommonResponse.createForSuccess(loginAccount);
        }
        return CommonResponse.createForError(ResponseCode.NEED_LOGIN.getCode(), "用户未登录，不能获取用户信息");
    }

    //注册
    @PostMapping("register")
    @ResponseBody
    public CommonResponse<AccountVO> registerAccount(AccountVO accountVO,HttpSession session){
        CommonResponse<AccountVO> response = accountService.registerAccount(accountVO);
        if (response.isSuccess()) {
            session.setAttribute("login_account", response.getData());
        }
        return response;
    }

    //此用户名是否存在
    @GetMapping("is_username_exist/{username}")
    @ResponseBody
    public CommonResponse<Boolean> isUsernameExist(@PathVariable("username")  String username) {
        return accountService.isUsernameExist(username);
    }

    //重置密码
    @PostMapping("reset_password")
    @ResponseBody
    public CommonResponse<Integer> restPassword(@RequestParam("username")  String username,
                                                @RequestParam("password") String password) {
        SignOn SignOn = new SignOn();
        SignOn.setUsername(username);
        SignOn.setPassword(password);
        return accountService.resetPassword(SignOn);
    }

    //修改账号信息
    @PostMapping("update_account_info")
    @ResponseBody
    public CommonResponse<AccountVO> updateAccountInfo(AccountVO accountVO) {
        return accountService.updateAccountInfo(accountVO);
    }

    //登出
    @RequestMapping("SingOut")
    @ResponseBody
    public CommonResponse<Boolean> SingOut(HttpSession session) {
        session.invalidate();
//        session.removeAttribute("login_account");
        return CommonResponse.createForSuccess(true);
    }

}
